package icu.yougan.trade.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import jakarta.annotation.PostConstruct;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author:Lee
 * @Date:2025/3/11 23:01
 * @Description:阿里云服务器上传
 **/
@Component
public class AliOSSUploadUtils
{
    // 配置注入字段（无需 static 修饰）
    @Value("${alioss.Ali_DOMAIN}")
    private String aliDomain;

    @Value("${alioss.endpoint}")
    private String endPoint;

    @Value("${alioss.access-key-id}")
    private String accessKeyId;

    @Value("${alioss.access-key-secret}")
    private String accessKeySecret;

    @Value("${alioss.bucket-name}")
    private String bucketName;

    /**
     * 上传文件到OSS
     * @param file 上传的文件
     * @return 文件访问URL
     */
    public String uploadImage(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename != null ?
                "." + FilenameUtils.getExtension(originalFilename) : "";
        String fileName = UUID.randomUUID().toString().replace("-", "") + ext;

        // 创建 OSS 客户端（每次使用新建实例）
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);

        try {
            // 上传文件
            ossClient.putObject(bucketName, fileName, file.getInputStream());
        } finally {
            // 确保关闭客户端
            ossClient.shutdown();
        }

        // 返回完整访问路径
        return aliDomain + "/" + fileName;
    }


}
